package com.yinhai.ta404.component.org.sysmg.resource.service.write.impl;

import com.alibaba.fastjson.JSONObject;
import com.yinhai.ta404.component.org.core.constant.OrgConstant;
import com.yinhai.ta404.component.org.core.service.impl.OrgBaseService;
import com.yinhai.ta404.component.org.core.utils.ExcludeChildrenUtil;
import com.yinhai.ta404.component.org.core.vo.TaResourceVo;
import com.yinhai.ta404.component.org.sysmg.resource.entity.TaResourcePo;
import com.yinhai.ta404.component.org.sysmg.resource.entity.TaResourceRestUrlPo;
import com.yinhai.ta404.component.org.sysmg.resource.mapper.read.ResourceOverlayReadMapper;
import com.yinhai.ta404.component.org.sysmg.resource.mapper.read.ResourceReadMapper;
import com.yinhai.ta404.component.org.sysmg.resource.mapper.read.RestUrlReadMapper;
import com.yinhai.ta404.component.org.sysmg.resource.mapper.write.ResourceWriteMapper;
import com.yinhai.ta404.component.org.sysmg.resource.mapper.write.RestUrlWriteMapper;
import com.yinhai.ta404.component.org.sysmg.resource.service.write.PageElementWriteService;
import com.yinhai.ta404.component.org.sysmg.resource.service.write.ResourceWriteService;
import com.yinhai.ta404.core.exception.AppException;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import com.yinhai.ta404.core.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service
@TaTransactional
public class ResourceWriteServiceImpl extends OrgBaseService implements ResourceWriteService {

    @Resource
    private ResourceReadMapper resourceReadMapper;
    @Resource
    private ResourceWriteMapper resourceWriteMapper;
    @Resource
    private RestUrlReadMapper restUrlReadMapper;
    @Resource
    private PageElementWriteService pageElementWriteService;
    @Resource
    private RestUrlWriteMapper restUrlWriteMapper;
    @Resource
    private ResourceOverlayReadMapper resourceOverlayReadMapper;

    public static final String BUTTON_TYPE = "2";

    private static final Logger logger = LoggerFactory.getLogger(ResourceWriteServiceImpl.class);


    @Override
    public TaResourceVo addResource(TaResourceVo vo) {
        TaResourcePo resourcePo = ObjectConversionUtil.convert(new TaResourcePo(), vo);

        if (ValidateUtil.isEmpty(resourcePo.getpResourceId())) {
            throw new AppException("上级功能资源为空，无法获取上级组织,新增功能资源失败！");
        }


        TaResourcePo parentResourcePo = resourceReadMapper.get(resourcePo.getpResourceId());
        if (ValidateUtil.isEmpty(parentResourcePo)) {
            if (logger.isWarnEnabled()) {
                logger.warn("功能资源创建失败，无法找到ID为{}的上级功能资源！", resourcePo.getpResourceId());
            }
            throw new AppException("功能资源创建失败，无法找到上级组织！");
        }
        if (OrgConstant.NO.equals(parentResourcePo.getEffective())) {
            throw new AppException("上级功能资源[" + parentResourcePo.getName() + "]已禁用，无法添加下级功能资源，请刷新页面！");
        }

        resourcePo.setResourceId(UUIDUtils.getUUID());
        resourcePo.setCreateDate(getSysDate());
        if (ValidateUtil.isEmpty(resourcePo.getWorkbench())) {
            resourcePo.setWorkbench(OrgConstant.NO);
        }
        if (ValidateUtil.isEmpty(resourcePo.getDisplay())) {
            resourcePo.setDisplay(OrgConstant.YES);
        }
        if (ValidateUtil.isEmpty(resourcePo.getUiAuthorityPolicy())) {
            resourcePo.setUiAuthorityPolicy(OrgConstant.RESOURCE_UI_AUTHORITYPOLICY_EXTENDS);
        }


        if (ValidateUtil.isEmpty(resourcePo.getEffective())) {
            resourcePo.setEffective(OrgConstant.YES);
        }


        if (ValidateUtil.isEmpty(resourcePo.getOrderNo())) {
            Integer newSortNo = resourceReadMapper.queryNextLevelMaxOrderNo(resourcePo.getpResourceId());
            if (ValidateUtil.isEmpty(newSortNo)) {
                newSortNo = OrgConstant.MIN_ORDERNO;
            } else {
                newSortNo += OrgConstant.ORDERNO_INTERVAL;
            }
            resourcePo.setOrderNo(newSortNo);
        }


        try {
            int resourceLevel = Integer.parseInt(parentResourcePo.getResourceLevel());
            resourceLevel += 1L;
            resourcePo.setResourceLevel(String.valueOf(resourceLevel));
        } catch (NumberFormatException e) {
            if (logger.isErrorEnabled()) {
                logger.error("无法新建功能资源{}，该功能资源的父级功能资源{}的资源层级错误!错误信息：{}", resourcePo.getName(), parentResourcePo.getName(), e.getMessage());
            }
        }
		if (StringUtils.isNoneBlank(resourcePo.getField01()) && resourcePo.getField01().equals(BUTTON_TYPE)){

			resourcePo.setResourceType(parentResourcePo.getResourceType());

			resourcePo.setDisplay(OrgConstant.NO);
		}
        validateForAdd(resourcePo);

        checkName(resourcePo, parentResourcePo);


        String newIdPath = parentResourcePo.getIdPath() + OrgConstant.PATH_SEPARATOR + resourcePo.getResourceId();
        resourcePo.setIdPath(newIdPath);

        String newNamePath = parentResourcePo.getNamePath() + OrgConstant.PATH_SEPARATOR + resourcePo.getName();
        resourcePo.setNamePath(newNamePath);

        resourceTypeAddRule(parentResourcePo, resourcePo);
        securityPolicyAddRule(parentResourcePo, resourcePo);
        resourceWriteMapper.insert(resourcePo);

        String restUrl = resourcePo.getRestUrl();
        String resourceId = resourcePo.getResourceId();
        if (ValidateUtil.isNotEmpty(restUrl)) {
            batchService.batchOperation(RestUrlWriteMapper.class, "addResourceRestUrl", new Object[]{analysisRestUrl(resourceId, restUrl)}, null);
        }

        orgOpLogEventPublish.pubResourceOpLogEvent(OrgConstant.OP_TYPE_RESOURCE_ADD, resourcePo.getResourceId(), JsonFactory.bean2json(resourcePo), OrgConstant.YES);
        return resourcePo.toVo();
    }

    private void checkName(TaResourcePo resourcePo, TaResourcePo parentResourcePo) {
        String name = resourcePo.getName();
        List<TaResourcePo> resourcePoList = resourceReadMapper.queryNextLevelChild(resourcePo.getpResourceId());
        if (ValidateUtil.isEmpty(resourcePoList)) {
            return;
        }
        resourcePoList = resourcePoList.stream().filter(po -> !resourcePo.getResourceId().equals(po.getResourceId())).collect(Collectors.toList());
        resourcePoList.forEach(po -> {
            if (po.getName().trim().equals(name.trim())) {
                if (logger.isWarnEnabled()) {
                    logger.warn("无法在同一功能资源-{}-下，创建名称相同的功能资源-{}！", parentResourcePo.getName(), name);
                }
                throw new AppException("无法在同一功能资源->" + parentResourcePo.getName() + "下，创建名称相同的功能资源-" + name + "！");
            }
        });
    }


    @Override
    public void update(TaResourceVo vo) {
        TaResourcePo resourcePo = ObjectConversionUtil.convert(new TaResourcePo(), vo);
        validateForEdit(resourcePo);
        TaResourcePo oldTaResourcePo = resourceReadMapper.get(vo.getResourceId());
        if (ValidateUtil.isEmpty(oldTaResourcePo)) {
            if (logger.isWarnEnabled()) {
                logger.warn("需要的修改的功能资源{}已经不存在，修改失败！", resourcePo.getName());
            }
            throw new AppException("需要的修改的功能资源" + resourcePo.getName() + "已经不存在，修改失败！");
        }
        String parentNamePath;
        resourcePo.setCreateDate(oldTaResourcePo.getCreateDate());
        resourcePo.setCreateUser(oldTaResourcePo.getCreateUser());
        resourcePo.setResourceLevel(oldTaResourcePo.getResourceLevel());
        resourcePo.setIdPath(oldTaResourcePo.getIdPath());
        if (ValidateUtil.isEmpty(resourcePo.getUiAuthorityPolicy())) {
            resourcePo.setUiAuthorityPolicy(OrgConstant.RESOURCE_UI_AUTHORITYPOLICY_EXTENDS);
        }

        if (OrgConstant.YES.equals(oldTaResourcePo.getEffective())
                && OrgConstant.NO.equals(resourcePo.getEffective())) {
            updateEffectiveResourceWithChild(oldTaResourcePo.getResourceId(), OrgConstant.NO);
            updatePageElementEffectiveByResourceIdWithChild(oldTaResourcePo.getResourceId(), OrgConstant.NO);
        }

        if (OrgConstant.NO.equals(oldTaResourcePo.getEffective())
                && OrgConstant.YES.equals(resourcePo.getEffective())) {
            if (OrgConstant.NO.equals(resourceReadMapper.get(oldTaResourcePo.getpResourceId()).getEffective())) {
                throw new AppException("功能资源" + resourcePo.getName() + "的上级功能资源为禁用状态，更新失败！");
            }
            updateEffectiveResourceWithChild(oldTaResourcePo.getResourceId(), OrgConstant.YES);
            updatePageElementEffectiveByResourceIdWithChild(oldTaResourcePo.getResourceId(), OrgConstant.YES);
        }


        List<TaResourceRestUrlPo> oldResourceUrlPoList = restUrlReadMapper.queryRestUrlByResourceId(resourcePo.getResourceId());
        List<TaResourceRestUrlPo> resourceRestUrlPoList = analysisRestUrl(resourcePo.getResourceId(), resourcePo.getRestUrl());

        if (ValidateUtil.isNotEmpty(oldResourceUrlPoList)) {
            Set<String> oldUrlIdSet = new HashSet<>();
            Set<String> oldAloneAuthIdSet = new HashSet<>();
            oldResourceUrlPoList.forEach(po -> {
                oldUrlIdSet.add(po.getUrlId());

                if (OrgConstant.YES.equals(po.getAuthorityPolicy())) {
                    oldAloneAuthIdSet.add(po.getUrlId());
                }
            });
            Set<String> delOrChangeUrlIdSet = new HashSet<>();
            resourceRestUrlPoList.forEach(po -> {
                String urlId = po.getUrlId();
                if (oldAloneAuthIdSet.contains(urlId) && OrgConstant.NO.equals(po.getAuthorityPolicy())) {

                    delOrChangeUrlIdSet.add(urlId);
                }

                oldUrlIdSet.remove(urlId);
            });
            delOrChangeUrlIdSet.addAll(oldUrlIdSet);

            restUrlWriteMapper.deleteResourceRestUrl(resourcePo.getResourceId());

            eventPublish.publish(new ArrayList<>(delOrChangeUrlIdSet), OrgConstant.DELETE_REST_URL_AUTHORITY);
        }

        batchService.batchOperation(RestUrlWriteMapper.class, "addResourceRestUrl", new Object[]{resourceRestUrlPoList}, null);


        List<TaResourcePo> resourcePoList = resourceReadMapper.queryChild(resourcePo.getResourceId());
        String newNamePath;
        TaResourcePo parentResourcePo;

        if (rootConfig.getResourceRootId().equals(oldTaResourcePo.getResourceId())) {
            newNamePath = resourcePo.getName();
            parentResourcePo = null;
        } else {
            parentResourcePo = resourceReadMapper.get(oldTaResourcePo.getpResourceId());
            parentNamePath = parentResourcePo.getNamePath();
            newNamePath = parentNamePath + OrgConstant.PATH_SEPARATOR + resourcePo.getName();

            checkName(resourcePo, parentResourcePo);
        }
		if (StringUtils.isNoneBlank(resourcePo.getField01()) && resourcePo.getField01().equals(BUTTON_TYPE)){

			if (parentResourcePo == null){
				throw new AppException("根菜单的菜单类型不能为按钮类型！");
			}
			resourcePo.setResourceType(parentResourcePo.getResourceType());

			resourcePo.setDisplay(OrgConstant.NO);
		}

        resourceTypeEditRule(parentResourcePo, resourcePo, resourcePoList);
        securityPolicyUpdateRule(parentResourcePo, resourcePo, resourcePoList);


        if (oldTaResourcePo.getName().trim().equals(resourcePo.getName().trim())) {
            resourceWriteMapper.update(resourcePo);
            return;
        }
        resourcePo.setNamePath(newNamePath);
        resourceWriteMapper.update(resourcePo);

        orgOpLogEventPublish.pubResourceOpLogEvent(OrgConstant.OP_TYPE_RESOURCE_EDIT, resourcePo.getResourceId(), JsonFactory.bean2json(oldTaResourcePo) + "->" + JsonFactory.bean2json(resourcePo), OrgConstant.YES);
        if (ValidateUtil.isEmpty(resourcePoList) || 1 == resourcePoList.size()) {
            return;
        }
        resourcePoList = resourcePoList.stream().filter(resourcePo1 -> !resourcePo.getResourceId().equals(resourcePo1.getResourceId())).collect(Collectors.toList());

        resourcePoList.forEach(resource -> resource.setNamePath(resource.getNamePath().replaceFirst(oldTaResourcePo.getNamePath(), newNamePath)));
        batchService.batchOperation(ResourceWriteMapper.class, "update", new Object[]{resourcePoList}, null);
    }

    @Override
    public void deleteBatch(List<String> resourceIds) {
        if (ValidateUtil.isEmpty(resourceIds)) {
            return;
        }
        if (resourceIds.contains(rootConfig.getResourceRootId())) {
            throw new AppException("所选功能资源包含根节点，顶级功能资源不能删除，操作失败！");
        }

        pageElementWriteService.deleteByResourceIdsWithChild(resourceIds);

        eventPublish.publish(resourceIds, OrgConstant.DELETE_BATCH_RESOURCE);

        batchService.batchOperation(RestUrlWriteMapper.class, "deleteResourceRestUrl", new Object[]{resourceIds}, null);

        batchService.batchOperation(ResourceWriteMapper.class, "deleteWithChild", new Object[]{resourceIds}, null);

        orgOpLogEventPublish.pubResourceOpLogEvent(OrgConstant.OP_TYPE_RESOURCE_DELETE, JsonFactory.bean2json(resourceIds), null, OrgConstant.YES);
    }

    @Override
    public void disableBatchWithChild(List<String> resourceIds) {
        if (ValidateUtil.isEmpty(resourceIds)) {
            throw new AppException("资源ID为空！操作失败！");
        }
        if (resourceIds.contains(rootConfig.getResourceRootId())) {
            throw new AppException("所选功能资源包含根节点，顶级功能资源不能禁用，操作失败！");
        }
        Integer maxCount = batchProperties.getMaxCount();
        if (resourceIds.size() > maxCount) {
            throw new AppException("操作数量超过最大限制：" + maxCount);
        }
        batchService.batchOperation(ResourceWriteMapper.class, "updateEffectiveResourcesWithChild", new Object[]{ OrgConstant.NO, resourceIds}, null);
        orgOpLogEventPublish.pubResourceOpLogEvent(OrgConstant.OP_TYPE_RESOURCE_FORBID, JsonFactory.bean2json(resourceIds), null, OrgConstant.NO);
    }

    @Override
    public void enableBatchWithChild(List<String> resourceIds) {
        if (ValidateUtil.isEmpty(resourceIds)) {
            throw new AppException("资源ID为空！操作失败！");
        }
        List<TaResourcePo> resourcePoList = resourceReadMapper.queryByIds(resourceIds);
        List<String> parentResourceIdList = ExcludeChildrenUtil.getParentIdByIdPath(resourcePoList
                .stream()
                .map(TaResourcePo::getIdPath)
                .collect(Collectors.toList()));
        if (resourceReadMapper.queryByIds(parentResourceIdList)
                .stream()
                .map(TaResourcePo::getEffective)
                .collect(Collectors.toList())
                .contains(OrgConstant.NO)) {
            throw new AppException("选择功能资源中存在该功能资源的上级功能资源处于禁用状态，无法启用！");

        }
        ;
        batchService.batchOperation(ResourceWriteMapper.class, "updateEffectiveResourcesWithChild", new Object[]{ OrgConstant.YES, resourceIds}, null);
        orgOpLogEventPublish.pubResourceOpLogEvent(OrgConstant.OP_TYPE_RESOURCE_START, JsonFactory.bean2json(resourceIds), null, OrgConstant.NO);
    }

    @Override
    public void updateSysCode(String newSysCode, String oldSysCode) {
        resourceWriteMapper.updateSysCodeBySysCode(newSysCode, oldSysCode);
    }

    @Override
    public void importResource() {

        throw new UnsupportedOperationException();
    }

    private void resourceTypeAddRule(TaResourcePo parentResourcePo, TaResourcePo resourcePo) {
        if (OrgConstant.RESOURCE_COMMON_MENU.equals(parentResourcePo.getResourceType())) {
            return;
        }
        if (!parentResourcePo.getResourceType().equals(resourcePo.getResourceType())) {
            throw new AppException("与上级功能资源菜单（资源）类型不一致，操作失败！");
        }
    }


    private void resourceTypeEditRule(TaResourcePo parentResourcePo, TaResourcePo resourcePo, List<TaResourcePo> childTaResourcePo) {
        if (null != parentResourcePo) {
            resourceTypeAddRule(parentResourcePo, resourcePo);
        }
        if (ValidateUtil.isEmpty(childTaResourcePo) || 1 == childTaResourcePo.size()) {
            return;
        }
        if (rootConfig.getResourceRootId().equals(resourcePo.getResourceId()) && !OrgConstant.RESOURCE_COMMON_MENU.equals(resourcePo.getResourceType())) {
            throw new AppException("根功能资源->" + resourcePo.getName() + "的资源类型只能为通用类功能资源！");
        }

        if (OrgConstant.RESOURCE_COMMON_MENU.equals(resourcePo.getResourceType())) {
            return;
        }
        Map<String, List<TaResourcePo>> map = new HashMap<>(10);
        int total = childTaResourcePo.size() - 1;
        childTaResourcePo.forEach(resourcePo1 -> {
            List<TaResourcePo> resourcePoList;
            if (!resourcePo1.getResourceId().equals(resourcePo.getResourceId())) {
                if (Objects.nonNull(map.get(resourcePo1.getResourceType()))) {
                    resourcePoList = map.get(resourcePo1.getResourceType());
                } else {
                    resourcePoList = new ArrayList<>();
                }
                resourcePoList.add(resourcePo1);
                map.put(resourcePo1.getResourceType(), resourcePoList);
            }
        });
        if (map.get(resourcePo.getResourceType()).size() == total) {
            return;
        }
        int errorNum = total - map.get(resourcePo.getResourceType()).size();
        throw new AppException("当前功能资源->" + resourcePo.getName() + "的子孙功能资源中存在"
                + errorNum + "个与当前菜单（资源）类型不一致的功能资源！");
    }


    private void securityPolicyAddRule(TaResourcePo parentResourcePo, TaResourcePo resourcePo) {
        if (OrgConstant.RESOURCE_SECURITYPOLICY_AUTHORITY_ACCESS.equals(parentResourcePo.getSecurityPolicy())) {
            return;
        }
        if (OrgConstant.RESOURCE_SECURITYPOLICY_LOGIN_ACCESS.equals(parentResourcePo.getSecurityPolicy())) {
            if (OrgConstant.RESOURCE_SECURITYPOLICY_LOGIN_ACCESS.equals(resourcePo.getSecurityPolicy())) {
                return;
            }
            throw new AppException("功能资源[ " + parentResourcePo.getName()
                    + "]下的功能资源授权策略只能为[登录可访问]，操作功能资源[" + resourcePo.getName() + "]的授权策略不正确！功能资源操作失败！");
        }
        if (OrgConstant.RESOURCE_SECURITYPOLICY_NOLOGIN_ACCESS.equals(parentResourcePo.getSecurityPolicy())) {
            if (OrgConstant.RESOURCE_SECURITYPOLICY_NOLOGIN_ACCESS.equals(resourcePo.getSecurityPolicy())) {
                return;
            }
            throw new AppException("功能资源[" + parentResourcePo.getName()
                    + "]下面的功能资源授权策略只能为[无需登录]即可访问，操作的功能资源[" + resourcePo.getName() + "]的功能资源授权策略不正确！功能资源操作失败！");
        }
        throw new AppException("未知的功能资源授权策略，无法操作功能资源！");
    }

    private void securityPolicyUpdateRule(TaResourcePo parentResourcePo, TaResourcePo resourcePo, List<TaResourcePo> childTaResourcePo) {
        if (null != parentResourcePo) {
            securityPolicyAddRule(parentResourcePo, resourcePo);
        }
        if (ValidateUtil.isEmpty(childTaResourcePo) || 1 == childTaResourcePo.size()) {
            return;
        }
        if (rootConfig.getResourceRootId().equals(resourcePo.getResourceId()) && !OrgConstant.RESOURCE_SECURITYPOLICY_AUTHORITY_ACCESS.equals(resourcePo.getSecurityPolicy())) {
            throw new AppException("根功能资源[" + resourcePo.getName() + "]的资源授权策略应为[授权可访问]的功能资源！");
        }

        if (OrgConstant.RESOURCE_SECURITYPOLICY_AUTHORITY_ACCESS.equals(resourcePo.getSecurityPolicy())) {
            return;
        }
        Map<String, List<TaResourcePo>> map = new HashMap<>(10);
        int total = childTaResourcePo.size() - 1;
        childTaResourcePo.forEach(resourcePo1 -> {
            List<TaResourcePo> resourcePoList;
            if (!resourcePo1.getResourceId().equals(resourcePo.getResourceId())) {
                if (Objects.nonNull(map.get(resourcePo1.getSecurityPolicy()))) {
                    resourcePoList = map.get(resourcePo1.getSecurityPolicy());
                } else {
                    resourcePoList = new ArrayList<>();
                }
                resourcePoList.add(resourcePo1);
                map.put(resourcePo1.getSecurityPolicy(), resourcePoList);
            }
        });
        if(map.get(OrgConstant.RESOURCE_SECURITYPOLICY_LOGIN_ACCESS) == null){
            map.put(OrgConstant.RESOURCE_SECURITYPOLICY_LOGIN_ACCESS, new ArrayList<>());
        }
        if(map.get(OrgConstant.RESOURCE_SECURITYPOLICY_NOLOGIN_ACCESS) == null){
            map.put(OrgConstant.RESOURCE_SECURITYPOLICY_NOLOGIN_ACCESS, new ArrayList<>());
        }
        if(map.get(OrgConstant.RESOURCE_SECURITYPOLICY_AUTHORITY_ACCESS) == null){
            map.put(OrgConstant.RESOURCE_SECURITYPOLICY_NOLOGIN_ACCESS, new ArrayList<>());
        }

        if (OrgConstant.RESOURCE_SECURITYPOLICY_LOGIN_ACCESS.equals(resourcePo.getSecurityPolicy())) {
            if (map.get(OrgConstant.RESOURCE_SECURITYPOLICY_LOGIN_ACCESS).size() == total) {
                return;
            }
            int errorNum = total - map.get(OrgConstant.RESOURCE_SECURITYPOLICY_LOGIN_ACCESS).size();
            throw new AppException("当前功能资源[" + resourcePo.getName() + "]的子孙功能资源中存在"
                    + errorNum + "个授权策略为[登录可访问]的功能资源！");
        }

        if (OrgConstant.RESOURCE_SECURITYPOLICY_NOLOGIN_ACCESS.equals(resourcePo.getSecurityPolicy())) {
            if (map.get(OrgConstant.RESOURCE_SECURITYPOLICY_NOLOGIN_ACCESS).size() == total) {
                return;
            }
            int errorNum = total - map.get(OrgConstant.RESOURCE_SECURITYPOLICY_NOLOGIN_ACCESS).size();
            throw new AppException("当前功能资源[" + resourcePo.getName() + "]的子孙功能资源中存在"
                    + errorNum + "个授权策略为[无需登录即可访问]的功能资源！");
        }
        throw new AppException("未知的功能资源类型，无法操作功能资源！");
    }

    private void validateForAdd(TaResourcePo resourcePo) {

        if (ValidateUtil.isEmpty(resourcePo.getpResourceId())) {
            throw new AppException("父级功能资源为空，添加失败!");
        }

        if (ValidateUtil.isEmpty(resourcePo.getName())) {
            throw new AppException("功能资源名称不能为空！");
        }


        if (ValidateUtil.isEmpty(resourcePo.getSecurityPolicy())) {
            throw new AppException("添加失败，安全策略错误，安全策略不能为空！");
        }

        if (ValidateUtil.isEmpty(resourcePo.getSecurityLevel())) {
            throw new AppException("添加失败，安全等级错误，安全等级不能为空！");
        }

        if (ValidateUtil.isEmpty(resourcePo.getResourceType())) {
            throw new AppException("添加失败，资源类型错误，资源类型不能为空！");
        }

        if (ValidateUtil.isEmpty(resourcePo.getUiAuthorityPolicy())) {
            throw new AppException("添加失败，界面元素授权策略错误，界面授权策略不能为空！");
        }

        if (ValidateUtil.isEmpty(resourcePo.getSysCode())) {
            throw new AppException("添加失败，所属系统错误，所属系统不能为空！");
        }

    }

    private void validateForEdit(TaResourcePo resourcePo) {

        if (ValidateUtil.isEmpty(resourcePo.getResourceId())) {
            throw new AppException("功能资源ID为空，无法修改该功能资源！");
        }



        if (ValidateUtil.isEmpty(resourcePo.getName())) {
            throw new AppException("功能资源名称为空，无法修改该功能资源！");
        }


        if (ValidateUtil.isEmpty(resourcePo.getSecurityPolicy())) {
            throw new AppException("添加失败，安全策略错误，安全策略不能为空！");
        }

        if (ValidateUtil.isEmpty(resourcePo.getSecurityLevel())) {
            throw new AppException("添加失败，安全等级错误，安全等级不能为空！");
        }

        if (ValidateUtil.isEmpty(resourcePo.getResourceType())) {
            throw new AppException("添加失败，资源类型错误，资源类型不能为空！");
        }

        if (ValidateUtil.isEmpty(resourcePo.getUiAuthorityPolicy())) {
            throw new AppException("添加失败，界面元素授权策略错误，界面授权策略不能为空！");
        }

        if (ValidateUtil.isEmpty(resourcePo.getSysCode())) {
            throw new AppException("添加失败，所属系统错误，所属系统不能为空！");
        }
    }

    private void updatePageElementEffectiveByResourceIdWithChild(String resourceId, String effective) {
        List<TaResourcePo> resourcePoList = resourceReadMapper.queryChild(resourceId);
        List<String> resourceIdList = new ArrayList<>();
        if (ValidateUtil.isEmpty(resourcePoList)) {
            return;
        }
        resourcePoList.forEach(resourcePo -> resourceIdList.add(resourcePo.getResourceId()));
        pageElementWriteService.updateEffectiveByResourceIdsWithChild(resourceIdList, effective);
    }

    private void updateEffectiveResourceWithChild(String resourceId, String effective) {
        List<TaResourcePo> resourcePoList = resourceReadMapper.queryChild(resourceId);
        List<String> resourceIdList = new ArrayList<>();
        if (ValidateUtil.isEmpty(resourcePoList)) {
            return;
        }
        resourcePoList.forEach(resourcePo -> resourceIdList.add(resourcePo.getResourceId()));
        batchService.batchOperation(ResourceWriteMapper.class, "updateEffectiveResource", new Object[]{effective, resourceIdList}, null);
    }

    @SuppressWarnings("unchecked")
    private List<TaResourceRestUrlPo> analysisRestUrl(String resourceId, String restUrls) {
        if (ValidateUtil.isEmpty(restUrls)) {
            return new ArrayList<>();
        }
        List<JSONObject> resourceRestUrlPoList = JsonFactory.json2bean(restUrls, List.class);
        List<String> restList = resourceRestUrlPoList.stream().map(po -> po.getString("id")).collect(Collectors.toList());
        if (restList.size() != new HashSet<>(restList).size()) {
            throw new AppException("RestUrl包含相同的服务地址!");
        }
        return resourceRestUrlPoList.stream().map(jsonObject -> {
            TaResourceRestUrlPo resourceRestUrlPo = new TaResourceRestUrlPo();
            String urlId = jsonObject.getString("id");
            if (ValidateUtil.isEmpty(urlId)) {
                throw new AppException("缺失URL标识参数，无法新增后端服务地址i！");
            } else {
                resourceRestUrlPo.setUrlId(urlId);
            }
            resourceRestUrlPo.setResourceId(resourceId);
//                resourceRestUrlPo.setRestUrl(jsonObject.getString("restUrl"));
//            resourceRestUrlPo.setUrlName(jsonObject.getString("urlName"));
            resourceRestUrlPo.setAuthorityPolicy(jsonObject.getString("authorityPolicy"));
            return resourceRestUrlPo;
        }).collect(Collectors.toList());
    }
}
